package process

import (
	"encoding/csv"
	"fmt"
	"github.com/lishimeng/go-log"
	"os"
	"path"
	"time"
)

func (c *AnalysisContext) procAnalysis() (hasNext bool) {

	log.Info("汇总关键词的各项指标")
	c.buildAnalysis()

	log.Info("打印关键词各项指标")
	log.Info("keyword\tuse\tshow\tclick\torder\tcost\ttotalSales")
	log.Info("-----------------------------------------------------------")
	for kw, s := range c.summaryMap {
		log.Info("%s\t%d\t%d\t%d\t%d\t%f\t%f", kw, s.Use, s.Show, s.Click, s.Order, s.Cost, s.Sales)
	}

	log.Info("计算关键词各项百分比指标")
	c.calcRate()

	log.Info("存储计算结果")
	c.persistence()

	hasNext = false
	return
}

func (c *AnalysisContext) buildAnalysis() {
	// keyword index
	// matrix: keyword:index:count
	for kw, indexList := range c.keywordsMap {
		s := Summary{Keyword: kw}
		c.summarize1(&s, indexList)
		c.summaryMap[kw] = s
	}
}

func (c *AnalysisContext) summarize1(s *Summary, indexList []int) {

	for _, index := range indexList {
		c.summarize2(s, index)
	}
}

func (c *AnalysisContext) summarize2(s *Summary, index int) {
	line := c.input[index]
	count := c.keywordCount[s.Keyword]
	s.Use = s.Use + int64(count)
	s.Show = s.Show + line.Show
	s.Click = s.Click + line.Click
	s.Order = s.Order + line.Order
	s.Sales = s.Sales + line.TotalSales
	s.Cost = s.Cost + line.Cost
}

func (c *AnalysisContext) calcRate() {
	var totalDataSize = len(c.input)
	for kw, s := range c.summaryMap {
		if totalDataSize > 0 {
			s.UseRate = float64(s.Use) / float64(totalDataSize) * 100
		}
		if s.Show > 0 {
			s.ClickThroughRate = float64(s.Click) / float64(s.Show) * 100
		}
		if s.Click > 0 {
			s.Cr = float64(s.Order) / float64(s.Click) * 100
		}
		if s.Sales > 0 {
			s.Acos = s.Cost / s.Sales * 100
		}
		if s.Cost > 0 {
			s.RoI = (s.Sales - s.Cost) / s.Cost * 100
		}
		c.summaryMap[kw] = s
	}
}

func (c *AnalysisContext) persistence() {
	var name = fmt.Sprintf("keyword_analysis_%d.csv", time.Now().Unix())
	fullpath := path.Join("./out", name)
	file, err := os.OpenFile(fullpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		log.Info(err)
		return
	}
	defer func() {
		_ = file.Close()
	}()
	w := csv.NewWriter(file)
	_ = w.Write([]string{"\xEF\xBB\xBF"}) // BOM(防止excel打开乱码)

	err = w.Write([]string{"keyword",
		"use", "show", "click", "order", "cost($)", "totalSales($)",
		"useRate(使用率%)", "CTR(点击率%)", "CR(转化率%)", "ACOS(花费比%越小越好)", "ROI(投入产出比%越大越好)",
	})
	if err != nil {
		log.Info(err)
		return
	}
	for _, s := range c.summaryMap {

		err = w.Write([]string{s.Keyword,
			fmt.Sprintf("%d", s.Use),
			fmt.Sprintf("%d", s.Show),
			fmt.Sprintf("%d", s.Click),
			fmt.Sprintf("%d", s.Order),
			fmt.Sprintf("%f", s.Cost),
			fmt.Sprintf("%f", s.Sales),
			fmt.Sprintf("%f", s.UseRate),
			fmt.Sprintf("%f", s.ClickThroughRate),
			fmt.Sprintf("%f", s.Cr),
			fmt.Sprintf("%f", s.Acos),
			fmt.Sprintf("%f", s.RoI),
		})
		if err != nil {
			log.Info(err)
			return
		}
	}

	w.Flush()
}
